/**
 * JAVACC DEMO 1.0
 */
package com.apache.ius.impl;

import com.apache.api.manager.PluginConnector;
import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.database.db.IDao;
import com.apache.database.model.MethodParam;
import com.apache.exception.BusinessException;
import com.apache.ius.IusSqlTools;
import com.apache.ius.plugin.CustomMethodPlugin;
import com.apache.tools.StrUtil;

import java.util.Map;

/**
 * description:  返回IUS处理结果插件
 *
 * @author dyhou 创建时间：2016-7-28
 */
public class ResultPublicForSqlPluginImpl implements PluginConnector {

    private IDao iusPubDao;

    private ProxyManager iusProxyManager;

    private ProxyManager netProxyManager;

    /**
     * TODO sqlKeyId待执行sqlID
     * resultType返回类型:obj单对象;其他为集合
     * 分页:rows必填
     *
     * @see com.apache.api.manager.PluginConnector#execute(com.apache.api.vo.ParamsVo)
     */
    public Object execute(ParamsVo paramVo) throws Exception {
        String key = String.valueOf(paramVo.getParams("sqlKeyId"));
        ResultEntity entity = new ResultEntity();
        entity.setResult("true");
        if (Validator.isNull(key)) {
            //entity.setMessage("缺少方法执行参数");
            key = "ByObjInfo";
            paramVo.setParams("sqlKeyId", "ByObjInfo");
        }
        MethodParam params = new MethodParam(key, "", "", IusSqlTools.SPANCENAME);
        Map<String, Object> map = paramVo.getParams();
        String resultType = String.valueOf(paramVo.getParams("resultType"));
        map.remove("resultType");

        try {
            if ("processSql".equalsIgnoreCase(resultType)) {
                paramVo.setKey("iusTransaction");
                paramVo.setParams("resultType", resultType);
                entity = (ResultEntity) iusProxyManager.saveInvoke(paramVo);
                if ("T".equalsIgnoreCase(entity.getResult())) {
                    paramVo.setParams("resultEntity", entity.getEntity());
                    IusSqlTools.getInstance().exeCustomPluginForAfter(paramVo, "after");
                    if (null != paramVo.getParams(CustomMethodPlugin.afterPluginReturn)) {
                        entity.setEntity(paramVo.getParams(CustomMethodPlugin.afterPluginReturn));
                    }
                }
            } else if ("objInfo".equals(resultType)) {
                paramVo.setKey("iusTransaction");
                paramVo.setParams("resultType", resultType);
                entity = (ResultEntity) iusProxyManager.doInvoke(paramVo);
                paramVo.setParams("resultEntity", entity.getEntity());
                IusSqlTools.getInstance().exeCustomPluginForAfter(paramVo, "after");
                if (null != paramVo.getParams(CustomMethodPlugin.afterPluginReturn)) {
                    entity.setEntity(paramVo.getParams(CustomMethodPlugin.afterPluginReturn));
                }
            } else if ("execSql".equalsIgnoreCase(resultType)) {
                execSql(entity, params, paramVo);
            } else if ("execInsertSql".equalsIgnoreCase(resultType)) {
                execInsertSql(entity, params, paramVo);
            } else {
                exeMarkSql(entity, params, map, resultType);
            }
        } catch (BusinessException e) {
            String exceptionStr = String.valueOf(paramVo.getParams("businessException"));
            if (Validator.isNotNull(exceptionStr)) {
                entity.setMessage(exceptionStr);
            } else {
                entity.setMessage(e.getMessage());
            }
            entity.setEntity("F");
        }
        params = null;
        paramVo = null;
        return entity;
    }

    /**
     * description:  生成动态修改语句
     * 参数:exe_rules样例:exe_rules=pub.proId:[pro.proId],pub.proNo:[pro.proNo]<br>
     * modelTypes样例:modelTypes=pro,pub,deal<br>
     * exeType sql语句类型:insert:插入,update:修改,del删除
     */
    private void execSql(ResultEntity entity, MethodParam params, ParamsVo paramVo) {
        String execSql = IusSqlTools.getInstance().cteageNativeSql(paramVo, "update");
        if (Validator.isNotNull(execSql)) {
            params.setParams("execSql", execSql);
            iusPubDao.select(params);
            String result = (String) params.getParamsByKey("result");
            if ("T".equals(result)) {
                entity.setEntity(result);
            } else {
                entity.setMessage("执行失败");
            }
        } else {
            entity.setMessage("缺少方法执行参数");
        }
    }

    /**
     * description:  生成动态插入语句
     * 参数:exe_rules样例:exe_rules=pub.proId:[pro.proId],pub.proNo:[pro.proNo]<br>
     * modelTypes样例:modelTypes=pro,pub,deal<br>
     * exeType sql语句类型:insert:插入,update:修改,del删除
     */
    private void execInsertSql(ResultEntity entity, MethodParam params, ParamsVo paramVo) {
        String execSql = IusSqlTools.getInstance().cteageNativeSql(paramVo, "insert");
        if (Validator.isNotNull(execSql)) {
            params.setParams("execSql", execSql);
            iusPubDao.select(params);
            String result = (String) params.getParamsByKey("result");
            if ("T".equals(result)) {
                entity.setEntity(result);
            } else {
                entity.setMessage("执行失败");
            }
        } else {
            entity.setMessage("缺少方法执行参数");
        }
    }

    private void exeMarkSql(ResultEntity entity, MethodParam params, Map<String, Object> map,
            String resultType) {
        String val = String.valueOf(map.get("resultObjType"));
        if (!Validator.isEmpty(netProxyManager)) {//调用农易通接口
            params.setSpanceName("com.iussoft.net.trans.TransPublic");
        }
        if ("obj".equalsIgnoreCase(val)) {
            params.setParams(map);
            Object obj = iusPubDao.selectSingle(params);
            entity.setEntity(obj);
        } else if ("count".equalsIgnoreCase(resultType)) {
            params.setParams(map);
            long obj = iusPubDao.count(params);
            entity.setEntity(obj);
        } else {
            params.setResultCache(false);
            String rows = String.valueOf(map.get("rows"));
            map.remove("rows");
            if (Validator.isNull(rows)) {
                params.setParams(map);
                entity.setEntity(iusPubDao.select(params));
            } else {
                params.setPageIndex(
                        Integer.valueOf(StrUtil.doNull(String.valueOf(map.get("page")), "1")));
                map.remove("page");
                params.setParams(map);
                params.setPageSize(Integer.valueOf(rows));
                entity.setEntity(iusPubDao.pageSelect(params));
            }
            entity.setMessage("查询成功");
        }
    }

    public void setIusPubDao(IDao iusPubDao) {
        this.iusPubDao = iusPubDao;
    }

    public void setIusProxyManager(ProxyManager iusProxyManager) {
        this.iusProxyManager = iusProxyManager;
    }

    public void setNetProxyManager(ProxyManager netProxyManager) {
        this.netProxyManager = netProxyManager;
    }

}
